package com.itheima.controller.admin;

import com.itheima.constant.JwtClaimsConstant;
import com.itheima.dto.SysUserLoginDTO;
import com.itheima.entity.SysUser;
import com.itheima.properties.JwtProperties;
import com.itheima.result.ErrorResult;
import com.itheima.result.Result;
import com.itheima.service.UserLoginService;
import com.itheima.utils.JwtUtil;
import com.itheima.vo.SysUserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author iTaotao
 * @date 2023/7/26 0:52
 * @desciption: 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/index")
public class UserLoginController {
    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private JwtProperties jwtProperties;

    @PostMapping("/login")
    public Result<SysUserLoginVO> login(@RequestBody SysUserLoginDTO sysUserLoginDTO) {
        log.info("用户登录: {}", sysUserLoginDTO);
        SysUser sysUser = userLoginService.login(sysUserLoginDTO);


        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, sysUser.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        SysUserLoginVO sysLoginVO = SysUserLoginVO.builder()
                .id(sysUser.getId())
                .loginName(sysUser.getLoginName())
                .name(sysUser.getName())
                .token(token)
                .build();

        return Result.success(sysLoginVO);

    }

}
